package com.zisuyi.game.sdk.library.login.impl

import android.app.Application
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.LifecycleOwner
import com.facebook.*
import com.facebook.AccessToken
import com.facebook.appevents.AppEventsLogger
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.zisuyi.game.sdk.library.login.BaseGameLogin
import com.zisuyi.game.sdk.library.login.IGameLogin


/**
 * faceBook登录
 */
internal class GameLoginFacebookImpl(manager: FragmentManager, lifecycleOwner: LifecycleOwner) :
        BaseGameLogin(manager, lifecycleOwner) {
    companion object {
        fun init(application: Application) {
            FacebookSdk.setAutoInitEnabled(true)
            FacebookSdk.fullyInitialize()
            AppEventsLogger.activateApp(application)
        }

        internal fun lastLoginUserInfo(): IGameLogin.UserInfo? {
            //判断facebook是否登录
            val faceBook = AccessToken.getCurrentAccessToken()
            println("facebook------------> $faceBook")
            return if (faceBook != null && !faceBook.isExpired) {
                //facebook登录成功
                toUserInfo(faceBook)
            } else {
                null
            }
        }

        internal fun logout() {
            LoginManager.getInstance().logOut()
        }

        private fun toUserInfo(token: AccessToken): IGameLogin.UserInfo {
            val profile = Profile.getCurrentProfile()
            val headPic = profile?.getProfilePictureUri(400, 400)?.toString()
            val name = profile?.name
            val uid = token.userId
            val uToken = token.token
            return IGameLogin.UserInfo(uid, uToken, IGameLogin.LOGIN_FACEBOOK, name, headPic)
        }

        private const val ME_ENDPOINT = "/me"

        /**
         * 获取其他信息，暂时不用
         */
        private fun makeUserRequest(callback: GraphRequest.Callback?) {
            val params = Bundle()
            params.putString("fields", "picture,name,id,email,permissions")
            val request = GraphRequest(
                    AccessToken.getCurrentAccessToken(), ME_ENDPOINT, params, HttpMethod.GET, callback
            )
            request.executeAsync()
        }
    }

    private val callbackManager = CallbackManager.Factory.create()

    init {
        initLogin()
    }

    override fun startLogin() {
        val info = lastLoginUserInfo()
        if (info == null) {
            val permission =
                    mutableListOf("public_profile", "email")
            LoginManager.getInstance().logInWithReadPermissions(callFragment, permission)
        } else {
            listeners.forEach {
                it.onSuccess(info, IGameLogin.LOGIN_FACEBOOK)
            }
        }
    }

    override fun logOut() {
        logout()
    }

    private fun initLogin() {
        LoginManager.getInstance().registerCallback(
                callbackManager,
                object : FacebookCallback<LoginResult?> {
                    override fun onSuccess(result: LoginResult?) {
                        val token = result?.accessToken
                        if (token?.token.isNullOrBlank() || token == null) {
                            loginCancel()
                        } else {
                            loginSuccess(token)
                        }
                    }

                    override fun onCancel() {
                        loginCancel()
                    }

                    override fun onError(error: FacebookException) {
                        loginFail(error)
                    }
                })
    }

    private fun loginCancel() {
        listeners.forEach {
            it.onCancel(IGameLogin.LOGIN_FACEBOOK)
        }
    }

    private fun loginFail(error: Throwable) {
        listeners.forEach {
            it.onError(error, IGameLogin.LOGIN_FACEBOOK)
        }
    }

    private fun loginSuccess(token: AccessToken) {
        val info = toUserInfo(token)
        listeners.forEach {
            it.onSuccess(info, IGameLogin.LOGIN_FACEBOOK)
        }
    }

    override fun onActivityResultByFragment(requestCode: Int, resultCode: Int, data: Intent?) {
        callbackManager.onActivityResult(requestCode, resultCode, data)
    }
}